import sys
sys.path.append("../utils")
config_path = "./config.cfg"

import ConfigParser
import time
import re
import datetime as dt
import tables as tb
from matplotlib.dates import date2num
from matplotlib.dates import num2date

def get_h5data(h5file):
    h5file = tb.openFile((h5file), mode='r')
    turbs = h5file.root._v_children
    return turbs

def filter_h5data(turbine_data, filt_strings, startnum=None, steplen=None, stopnum=-1):
    for i, filt in enumerate(filt_strings):
        if i == 0:
            filt_string = filt
        else:
            filt_string += " & " + filt
    filt_data = turbine_data.readWhere(filt_string, start=startnum, stop=stopnum, step=steplen)
    return filt_data

def main():
    start_time = time.time()
    config = ConfigParser.ConfigParser()
    config.read(config_path)
    bin_path = config.get("options", "bin_path")
    alarm_type = "active-alarm-no"
    h5file = bin_path + alarm_type + ".h5"
    data = get_h5data(h5file)
    alarm_key = "ActiveAlarmNo"
    start_day = dt.datetime(2006,1,1)
    stop_day = dt.datetime(2012,1,1)
    diff_alarms = {}
    total_num_of_alarms = 0
    for turbine in data.keys():
        time_range = ["(Time >= " + str(date2num(start_day)) + ")", "(Time < " + str(date2num(stop_day)) + ")"]
        filt_data = filter_h5data(data[turbine], time_range)
        for alarm, tid in filt_data:
            #print alarm
            #print tid
            #return
            total_num_of_alarms += 1
            if alarm in diff_alarms.keys():
                diff_alarms[alarm] += 1
                pass
            else:
                diff_alarms[alarm] = 1
    # Print alarms according to occurrence

    print len(diff_alarms.keys())

    """
    for w in sorted(diff_alarms, key=diff_alarms.get, reverse=True):
        print w, diff_alarms[w]
    """
    num_of_temp = 0
    num_of_q8 = 0
    num_in_gear = 0
    num_not_grouped = 0
    num_of_electrical = 0
    num_of_pitch = 0
    num_of_yaw = 0
    num_of_ctrl = 0
    num_of_rotor_gen = 0
    num_of_hydralic = 0
# New groups
    num_of_pitch_rotor = 0
    num_of_converter = 0
    num_of_gearbox = 0
    num_of_generator = 0
    num_of_grid_control = 0
    num_of_yaws = 0
    num_of_others = 0
# .*vcms.*
    alarms = diff_alarms.keys()
    alarms.remove('Bad')
    alarms.remove('Pause')
    alarms.remove('Comm Fail')
    alarms.remove('Emergency')
    alarms.remove('I/O Timeout')
    alarms.remove('Coercion Failed')
    alarms.remove('Stop')
    alarms.remove('Shutdown')
    alarms.remove('Pt Created')
    alarms.remove('Remote Reboot')
    alarms.remove('Turbine OK')
    alarms.remove('Pause over RCS')
    alarms.remove('Too many auto-restarts:_____')
    alarms.remove('High windspeed: __._ m/s')
    alarms.remove('New SERVICE state: _. ____')
    alarms.remove('[Error 202. ______.______]')
    alarms.remove('US error. Turbine stopped')

    for alarm in alarms:
        match = re.search(r"^(.*pitch.*|.*rotor.*|.*ctrlv.*|.*ctrl.*)*(.*converter.*)*(.*gear.*)*(.*gen.*)*(.*grid.*|.*vcms.*|.*vcs.*)*(.*yaw.*)*", alarm.lower())
        if match.group(1):
            num_of_pitch_rotor += 1
        if match.group(2):
            num_of_converter += 1
        if match.group(3):
            num_of_gearbox += 1
        if match.group(4):
            num_of_generator += 1
        if match.group(5):
            num_of_grid_control += 1
        if match.group(6):
            num_of_yaws += 1
        if not (match.group(1) or match.group(2) or match.group(3) or match.group(4) or match.group(5) or match.group(6)):
            num_of_others += 1
            print alarm

    print num_of_pitch_rotor
    print num_of_converter
    print num_of_gearbox
    print num_of_generator
    print num_of_grid_control
    print num_of_yaws
    print num_of_others

    print "new analysis"
    from collections import defaultdict
    new_list = defaultdict(list)
    for alarm in alarms:
        match = re.search(r"^(.*thermo.*|.*temp.*|.*termo.*|.*t53.*|.*varm.*|.*cooling.*)*(.*q8.*|.*q7.*|.*breaker.*)*(.*gear.*|.*lubrication.*|.*fine.*)*(.*power.*|.*cur.*|.*volt.*|.*phase.*|.*charge.*)*(.*pitch.*|.*ctrl.*)*(.*yaw.*)*(.*vcms.*|.*vcpm.*|.*vcs.*|.*encoder.*)*(.*rotor.*|.*gen.*|.*rpm.*|.*brake.*)*(.*hydr.*|.*leakage.*|.*pressure.*)*", alarm.lower())
        if match.group(1):
            #num_of_temp += 1
            num_of_temp += diff_alarms[alarm]
            new_list["Temperature"].append(alarm)
        if match.group(2):
            #num_of_q8 += 1
            num_of_q8 += diff_alarms[alarm]
            new_list["Breaker"].append(alarm)
        if match.group(3):
            #num_in_gear += 1
            num_in_gear += diff_alarms[alarm]
            new_list["Gear"].append(alarm)
        if match.group(4):
            #num_of_electrical += 1
            num_of_electrical += diff_alarms[alarm]
            new_list["Electrical"].append(alarm)
        if match.group(5):
            #num_of_pitch += 1
            num_of_pitch += diff_alarms[alarm]
            new_list["Pitch"].append(alarm)
        if match.group(6):
            #num_of_yaw += 1
            num_of_yaw += diff_alarms[alarm]
            new_list["Yaw"].append(alarm)
        if match.group(7):
            #num_of_ctrl += 1
            num_of_ctrl += diff_alarms[alarm]
            new_list["Controller"].append(alarm)
        if match.group(8):
            #num_of_rotor_gen += 1
            num_of_rotor_gen += diff_alarms[alarm]
            new_list["Generator"].append(alarm)
        if match.group(9):
            num_of_hydralic += diff_alarms[alarm]
            new_list["Hydraulic"].append(alarm)
        if not (match.group(1) or match.group(2) or match.group(3) or match.group(4) or match.group(5) or match.group(6) or match.group(7) or match.group(8) or match.group(9)):
            #num_not_grouped += 1
            num_not_grouped += diff_alarms[alarm]
            new_list["Others"].append(alarm)
            print alarm, diff_alarms[alarm]
    sorted_alarms = num_of_temp + num_of_q8 + num_in_gear + num_of_pitch + num_of_yaw + num_of_ctrl + num_of_rotor_gen + num_of_hydralic + num_not_grouped
    sorted_alarms = float(sorted_alarms)
    print "Temperature",
    print num_of_temp,
    print num_of_temp / sorted_alarms * 100
    print "Breaker",
    print num_of_q8,
    print num_of_q8 / sorted_alarms * 100
    print "Gear",
    print num_in_gear,
    print num_in_gear / sorted_alarms * 100
    print "Pitch",
    print num_of_pitch
    print num_of_pitch / sorted_alarms * 100
    print "Yaw",
    print num_of_yaw,
    print num_of_yaw / sorted_alarms * 100
    print "Controller",
    print num_of_ctrl,
    print num_of_ctrl / sorted_alarms * 100
    print "Generator",
    print num_of_rotor_gen,
    print num_of_rotor_gen / sorted_alarms * 100
    print "Hydraulic",
    print num_of_hydralic,
    print num_of_hydralic / sorted_alarms * 100
    print "Others",
    print num_not_grouped,
    print num_not_grouped / sorted_alarms * 100
    print "Total",
    print sorted_alarms,
    print sorted_alarms / total_num_of_alarms * 100
    print "Number of different alarms:",
    print len(diff_alarms)
    print "Total number of alarms:",
    print total_num_of_alarms
    for alarms in new_list:
        print alarms,
        print "--------------------"
        for tag in new_list[alarms]:
            print tag



    print "Done in:",
    print (time.time() - start_time)
    return




if __name__=='__main__':
    main()


"""
def anal_of_alarmtxt():
    start_time = time.time()
    config = ConfigParser.ConfigParser()
    config.read(config_path)
    bin_path = config.get("options", "bin_path")
    alarm_type = "alarm-txt"
    h5file = bin_path + alarm_type + ".h5"
    data = get_h5data(h5file)
    alarm_key = "AlarmTxt"
    start_day = dt.datetime(2006,1,1)
    stop_day = dt.datetime(2012,1,1)
    diff_alarms = {}
    total_num_of_alarms = 0
    for turbine in data.keys():
        time_range = ["(Time >= " + str(date2num(start_day)) + ")", "(Time < " + str(date2num(stop_day)) + ")"]
        filt_data = filter_h5data(data[turbine], time_range)
        for alarm in filt_data[alarm_key]:
            total_num_of_alarms += 1
            if alarm in diff_alarms.keys():
                diff_alarms[alarm] += 1
                pass
            else:
                diff_alarms[alarm] = 1
    for w in sorted(diff_alarms, key=diff_alarms.get, reverse=True):
        print w, diff_alarms[w]
    print len(diff_alarms)
    print total_num_of_alarms
    print "Done in:",
    print (time.time() - start_time)
    return
"""
